var margin = {top: 20, right: 0, bottom: 0, left: 0},
    width = 960,
    height = 500 - margin.top - margin.bottom,
    formatNumber = d3.format(",d"),
    transitioning;

var x = d3.scale.linear()
    .domain([0, width])
    .range([0, width]);

var y = d3.scale.linear()
    .domain([0, height])
    .range([0, height]);

var treemap = d3.layout.treemap()
    .children(function(d, depth) { return depth ? null : d._children; })
    .sort(function(a, b) { return a.value - b.value; })
    .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
    .round(false);

var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.bottom + margin.top)
    .style("margin-left", -margin.left + "px")
    .style("margin.right", -margin.right + "px")
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .style("shape-rendering", "crispEdges");

var grandparent = svg.append("g")
    .attr("class", "grandparent");

grandparent.append("rect")
    .attr("y", -margin.top)
    .attr("width", width)
    .attr("height", margin.top);

grandparent.append("text")
    .attr("x", 6)
    .attr("y", 6 - margin.top)
    .attr("dy", ".75em");

d3.json("flare.json", function(root) {
  initialize(root);
  accumulate(root);
  layout(root);
  display(root);

  function initialize(root) {
    root.x = root.y = 0;
    root.dx = width;
    root.dy = height;
    root.depth = 0;
  }

  // Aggregate the values for internal nodes. This is normally done by the
  // treemap layout, but not here because of our custom implementation.
  // We also take a snapshot of the original children (_children) to avoid
  // the children being overwritten when when layout is computed.
  function accumulate(d) {
    return (d._children = d.children)
        ? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
        : d.value;
  }

  // Compute the treemap layout recursively such that each group of siblings
  // uses the same size (1×1) rather than the dimensions of the parent cell.
  // This optimizes the layout for the current zoom state. Note that a wrapper
  // object is created for the parent node for each group of siblings so that
  // the parent’s dimensions are not discarded as we recurse. Since each group
  // of sibling was laid out in 1×1, we must rescale to fit using absolute
  // coordinates. This lets us use a viewport to zoom.
  function layout(d) {
    if (d._children) {
      treemap.nodes({_children: d._children});
      d._children.forEach(function(c) {
        c.x = d.x + c.x * d.dx;
        c.y = d.y + c.y * d.dy;
        c.dx *= d.dx;
        c.dy *= d.dy;
        c.parent = d;
        layout(c);
      });
    }
  }

  function display(d) {
    grandparent
        .datum(d.parent)
        .on("click", transition)
      .select("text")
        .text(name(d));

    var g1 = svg.insert("g", ".grandparent")
        .datum(d)
        .attr("class", "depth");

    var g = g1.selectAll("g")
        .data(d._children)
      .enter().append("g");

    g.filter(function(d) { return d._children; })
        .classed("children", true)
        .on("click", transition);

    g.selectAll(".child")
        .data(function(d) { return d._children || [d]; })
      .enter().append("rect")
        .attr("class", "child")
        .call(rect);

    g.append("rect")
        .attr("class", "parent")
        .call(rect)
      .append("title")
        .text(function(d) { return formatNumber(d.value); });

    g.append("text")
        .attr("dy", ".75em")
        .text(function(d) { return d.name; })
        .call(text);

    function transition(d) {
      if (transitioning || !d) return;
      transitioning = true;

      var g2 = display(d),
          t1 = g1.transition().duration(750),
          t2 = g2.transition().duration(750);

      // Update the domain only after entering new elements.
      x.domain([d.x, d.x + d.dx]);
      y.domain([d.y, d.y + d.dy]);

      // Enable anti-aliasing during the transition.
      svg.style("shape-rendering", null);

      // Draw child nodes on top of parent nodes.
      svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; });

      // Fade-in entering text.
      g2.selectAll("text").style("fill-opacity", 0);

      // Transition to the new view.
      t1.selectAll("text").call(text).style("fill-opacity", 0);
      t2.selectAll("text").call(text).style("fill-opacity", 1);
      t1.selectAll("rect").call(rect);
      t2.selectAll("rect").call(rect);

      // Remove the old node when the transition is finished.
      t1.remove().each("end", function() {
        svg.style("shape-rendering", "crispEdges");
        transitioning = false;
      });
    }

    return g;
  }

  function text(text) {
    text.attr("x", function(d) { return x(d.x) + 6; })
        .attr("y", function(d) { return y(d.y) + 6; });
  }

  function rect(rect) {
    rect.attr("x", function(d) { return x(d.x); })
        .attr("y", function(d) { return y(d.y); })
        .attr("width", function(d) { return x(d.x + d.dx) - x(d.x); })
        .attr("height", function(d) { return y(d.y + d.dy) - y(d.y); });
  }

  function name(d) {
    return d.parent
        ? name(d.parent) + "." + d.name
        : d.name;
  }
});


'use strict';

import app from 'app';

// 窗口大小改变时重绘热力地图
app.directive('treeMapResize', ['$rootScope', '$timeout', function($rootScope, $timeout) {
    return {
        restrict: 'A',
        scope: true,
        compile: function(tElem, tAttr, transclude) {
            let $main = $('#mainContent'),
                $treemapTab = $('#treemap-tab'), // left tab navigation
                $treemapView = $('#treemap-view'); // right treemap part

            function render() {
                let width = $main.width();
                let height = $main.height();

                $treemapTab.height(height - 1);
                // 重绘热力地图
                $treemapView.height(height);
                $treemapView.width(width - $treemapTab.width() - 1);
            }
            return {
                pre: function preLink(scope, elem, attrs) {
                    $timeout(function() {
                        render();
                        // console.log('treemap-directive preLink reRender.');
                    }, 100);
                },
                post: function postLink(scope, elem, attrs) {
                    scope.$on('resizeWindow', function() {
                        $timeout(function() {
                            render();
                            // console.log('treemap-directive postLink reRender.');
                            $rootScope.$broadcast('treemapView.resizeUpdate');
                        }, 100);
                    });
                }
            };
        }
    };
}]);

/**
 * 渲染treemap图的指令
 */
app.directive('renderTreeMap', ['$state', '$stateParams', '$timeout', 'treemapService', function($state, $stateParams, $timeout, treemapService) {
    return {
        restrict: 'A',
        link: link
    };

    function link(scope, elem, attr) {
        scope.$on('treemapView.renderTreeMap', function(e, data) {
            $timeout(function() {
                let w = parseInt($("#treemap-view").width());
                let h = parseInt($("#mainContent").height());

                let node = treemapService.getCurrentNode();
                // console.log('%c [treemap-directive]renderTreeMap height: ', 'color:#0F9;', h, 'width: ', w);
                renderTreeMap(data, node, scope, { width: w, height: h });
            });
        });
    }
    /**
     * 渲染treemap图
     * @param msg , {data: treedata, tab: $scope.treemapTab}
     * @param node
     * @param scope
     */
    function renderTreeMap(msg, node, scope, size) {
        // console.log('%c [treemap-directive]renderTreeMap.', 'color:#F09;');

        var treedata = msg.data,
            tab = msg.tab,
            tmName = '',
            tmId = '';

        //console.log('msg:', msg, 'treemapdata:', treedata, 'tab:', tab);
        // console.log('[treemap-directive]renderTreeMap size:', size);

        switch (tab) {
            case 'GN':
                tmName = '所有概念';
                tmId = 'all_concept';
                break;
            case 'HY':
                tmName = '所有行业';
                tmId = 'all_industry';
                break;
            case 'DY':
                tmName = '所有地域';
                tmId = 'all_geography';
                break;
            case 'ZJHHY':
                tmName = '所有证监会行业';
                tmId = 'all_security';
                break;
        }

        scope.$evalAsync(function() {
            d3.select(".treemapsvg").remove();

            var indexNode = node;

            var margin = { top: 26, right: 0, bottom: 0, left: 0 },
                width = size.width,
                height = size.height - margin.top - margin.bottom,
                transitioning;

            var svg = d3.select("#treemapContainer").append("svg")
                .attr("class", "treemapsvg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.bottom + margin.top)
                .style("margin-left", -margin.left + "px")
                .style("margin-right", -margin.right + "px")
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                .style("shape-rendering", "crispEdges");

            var alldata = [];


            var maxGrids = size.width * size.height / 4500; //2982;

            //var _treedata = treedata.slice(0,maxGrids);
            treedata.forEach(function(d) {
                //d.percent = d.change_rate;
                d.children = d.symbol_list;
                d.type = "gn";
                d.numOfStock = d.children.length;
                d.children = d.children.slice(0, maxGrids);
                d.children.forEach(function(c) {
                    c.value = Math.pow(c.circulation_value, 0.1) / Math.pow(d.numOfStock, 0.7);
                    //c.value = 1/d.numOfStock;
                    c.children = c.symbol_list;
                    c.type = "stock";
                    alldata.push(c.change_rate);
                });
            });

            var fullTreeData = { "children": treedata, "name": tmName, "id": tmId };

            fullTreeData["min"] = d3.min(alldata);
            fullTreeData["max"] = d3.max(alldata);
            // 设置矩形框的填充颜色
            let rectColor = d3.scale.pow()
                .exponent(0.6)
                .domain([-10, 0, 10])
                .range(["#009933", "#FFF", "#F33939"]);
                // .range(["#0F0", "#8F8", "#FFF", "#F88", "#F00"]);

            var x = d3.scale.linear()
                .domain([0, width])
                .range([0, width]);

            var y = d3.scale.linear()
                .domain([0, height])
                .range([0, height]);

            var treemap = d3.layout.treemap()
                .children(function(d, depth) {
                    return depth ? null : d._children;
                })
                .sort(function(a, b) {
                    return a.value - b.value;
                })
                .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
                .round(false);

            var grandparent = svg.append("g")
                .attr("class", "grandparent");

            grandparent.append("rect")
                .attr("y", -margin.top)
                .attr("width", width)
                .attr("height", margin.top)
                .attr("class", "treerect");

            grandparent.append("text")
                .attr("x", 6)
                .attr("y", 6 - margin.top)
                .attr("dy", "11px")
                .style("font-size", "11px")
                .style("font-weight", "bold")
                .style("fill", "black");

            //data related
            initialize(fullTreeData);
            accumulate(fullTreeData);
            layout(fullTreeData);
            display(fullTreeData);

            /**
             * 初始化页面大小
             * @param root
             */
            function initialize(root) {
                root.x = root.y = 0;
                root.dx = width;
                root.dy = height;
                root.depth = 0;
                // rectColor.domain([root.min, root.min / 2, 0, root.max / 2, root.max]);
            }

            /**
             * 累积坐标
             * @param d
             * @returns {*}
             */
            function accumulate(d) {
                //d._children = d.children;
                //d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0);
                return (d._children = d.children) ? d.value = d.children.reduce(function(p, v) {
                    return p + accumulate(v);
                }, 0) : d.value;
            }

            /**
             * 动态布局
             * @param d
             */
            function layout(d) {
                if (d._children) {
                    treemap.nodes({ _children: d._children });
                    d._children.forEach(function(c) {
                        c.x = d.x + c.x * d.dx;
                        c.y = d.y + c.y * d.dy;
                        c.dx *= d.dx;
                        c.dy *= d.dy;
                        c.parent = d;
                        //c.parent = {'id': d.id, 'name': d.name, 'length': d._children.length};
                        layout(c);
                    });
                }
            }

            /**
             * 显示整个页面
             * @param d
             * @returns {*|Aggregate|SparkMD5|SparkMD5.ArrayBuffer|void|ServerResponse}
             */
            function display(d) {
                grandparent
                    .datum(d.parent)
                    .on("click", transition)
                    .select("text")
                    .text(name(d));

                var g1 = svg.insert("g", ".grandparent")
                    .datum(d)
                    .attr("class", "depth");

                var g = g1.selectAll("g")
                    .data(d._children)
                    .enter().append("g");

                g.filter(function(d) {
                        return d._children;
                    })
                    .classed("children", true)
                    .on("click", transition);

                g.selectAll(".child")
                    .data(function(d) {
                        return [d];
                    })
                    .enter().append("rect")
                    .attr("class", "child")
                    .call(rect);

                g.append("rect")
                    .attr("class", "parent treerect")
                    .style("cursor", "pointer")
                    .call(rect)
                    .on("click", function(d) {
                        if (d.type == "stock") {
                            $state.go('stockid', { stockid: d.id, company: $stateParams.company });
                        } else {
                            $state.transitionTo('treemap', { type: tab, id: d.id, company: $stateParams.company }, { notify: false, reload: $state.current });
                        }
                    })
                    .append("title")
                    .text(function(d) {
                        //if (d.percent < 0) {
                        //    return d.name + "下跌" + (-d.percent).toFixed(2) + "%";
                        //} else {
                        //    return d.name + "上涨" + (d.percent).toFixed(2) + "%";
                        //}
                        if (d.change_rate < 0) {
                            return d.name + "下跌" + (-d.change_rate).toFixed(2) + "%";
                        } else {
                            return d.name + "上涨" + (d.change_rate).toFixed(2) + "%";
                        }
                    });

                g.append("text")
                    .attr("dy", ".75em")
                    .style("font-size", "10px")
                    .call(text);

                g.append("text")
                    .attr("dy", ".75em")
                    .attr("class", "text_percent")
                    .style("font-size", "10px")
                    .call(percenttext);

                //console.log('%cindexNode:','color:#F09;', indexNode, ' id: ', indexNode.id, ' tmId:', tmId, 'treemapService.getIsUpdating():', treemapService.getIsUpdating());
                if (indexNode != null && indexNode.id !== tmId && treemapService.getIsUpdating()) {
                    // 通過currentNode的數據來渲染
                    //console.log('use currentNode:', d, 'len:', d._children);
                    // select target concept block
                    var targetNodeObj = {};
                    angular.forEach(d._children, function(v, k) {
                        if (v.id === indexNode.id) {
                            targetNodeObj = v;
                        }
                    });
                    if (!Object.keys(targetNodeObj).length) {
                        // can't find indexNode.id
                        transition_noAnanimate(d);
                        treemapService.setCurrentNode({ id: d.id, name: d.name, children: d._children });
                    } else {
                        transition_noAnanimate(targetNodeObj);
                        // set node and subscribe update
                        treemapService.setCurrentNode({ id: targetNodeObj.id, name: targetNodeObj.name, children: targetNodeObj._children });
                    }
                    treemapService.setIsUpdating(false);
                } else {
                    //console.log('%c ELSE','color:#09f;', 'false = (indexNode != null && indexNode.id !== tmId && treemapService.getIsUpdating())');
                    treemapService.setCurrentNode({ id: d.id, name: d.name, children: d._children });
                }

                // 带动画的切换所有概念页面或某一板块页面
                function transition(d) {
                    if (d != undefined && d.name == tmName) {
                        $state.transitionTo('treemap', { type: tab, company: $stateParams.company }, { notify: false, reload: $state.current });
                    }

                    if (transitioning || !d) return;
                    transitioning = true;

                    var g2 = display(d),
                        t1 = g1.transition().duration(750),
                        t2 = g2.transition().duration(750);

                    // Update the domain only after entering new elements.
                    x.domain([d.x, d.x + d.dx]);
                    y.domain([d.y, d.y + d.dy]);

                    // Enable anti-aliasing during the transition.
                    svg.style("shape-rendering", null);

                    // Draw child nodes on top of parent nodes.
                    svg.selectAll(".depth").sort(function(a, b) {
                        return a.depth - b.depth;
                    });

                    // Fade-in entering text.
                    g2.selectAll("text").style("font-size", "10px").style("fill-opacity", 0);

                    // Transition to the new view.

                    t1.selectAll("rect").call(rect);
                    t2.selectAll("rect").call(rect);

                    t1.selectAll("text").call(text).style("fill-opacity", 0);
                    t2.selectAll("text").call(text).style("fill-opacity", 1);

                    t1.selectAll(".text_percent").call(percenttext).style("fill-opacity", 0);
                    t2.selectAll(".text_percent").call(percenttext).style("fill-opacity", 1);

                    // Remove the old node when the transition is finished.
                    t1.remove().each("end", function() {
                        svg.style("shape-rendering", "crispEdges");
                        transitioning = false;
                    });
                }

                // 直接切换到所有概念页面或某一板块页面
                function transition_noAnanimate(d) {
                    if (transitioning || !d) return;
                    transitioning = true;

                    var g2 = display(d),
                        t1 = g1,
                        t2 = g2;

                    // Update the domain only after entering new elements.
                    x.domain([d.x, d.x + d.dx]);
                    y.domain([d.y, d.y + d.dy]);

                    // Enable anti-aliasing during the transition.
                    svg.style("shape-rendering", null);

                    // Draw child nodes on top of parent nodes.
                    svg.selectAll(".depth").sort(function(a, b) {
                        return a.depth - b.depth;
                    });

                    // Fade-in entering text.
                    g2.selectAll("text").style("font-size", "10px").style("fill-opacity", 0);

                    // Transition to the new view.

                    t1.selectAll("rect").call(rect);
                    t2.selectAll("rect").call(rect);

                    t1.selectAll("text").call(text).style("fill-opacity", 0);
                    t2.selectAll("text").call(text).style("fill-opacity", 1);

                    t1.selectAll(".text_percent").call(percenttext).style("fill-opacity", 0);
                    t2.selectAll(".text_percent").call(percenttext).style("fill-opacity", 1);

                    // Remove the old node when the transition is finished.
                    transitioning = false;
                    //t1.remove().each("end", function() {
                    //    svg.style("shape-rendering", "crispEdges");
                    //    transitioning = false;
                    //});
                }

                return g;
            }

            /**
             * 加载名称文本
             * @param text
             */
            function text(text) {
                text.attr("x", function(d) {
                        return x(d.x);
                    })
                    .attr("y", function(d) {
                        return y(d.y) + 9;
                    })
                    .text(function(d) {
                        return d.name;
                    })
                    .attr("dx", function(d) {
                        var cellwidth = x(d.x + d.dx) - x(d.x);
                        return cellwidth / 2;
                    })
                    .attr("dy", function(d) {
                        var cellheight = y(d.y + d.dy) - y(d.y);
                        return cellheight / 2 - 10;

                    })
                    .attr("text-anchor", "middle")
                    .style("opacity", function(d) {
                        var cellwidth = x(d.x + d.dx) - x(d.x);
                        var cellheight = y(d.y + d.dy) - y(d.y);
                        var textWidth = this.getComputedTextLength();

                        var cutNum = cellwidth / 13;
                        var cutText;
                        if (cutNum < d.name.length) {
                            cutText = d.name.slice(0, cutNum) + "...";
                        } else {
                            cutText = d.name;
                        }
                        d3.select(this).text(cutText);
                        return 1;

                        //if (cellwidth > textWidth && cellheight > 15) {
                        //    return 1;
                        //} else {
                        //
                        //}
                    })
                    .style("font-size", function(d) {
                        return "11px";
                    })
                    .style("font-family", "微软雅黑")
                    .style("font-weight", "bold")
                    .style("fill", function(d) {
                        return getColor(d);
                    });
            }

            function getColor(d) {
                var threshold = 1.45;
                if (d.change_rate < -5 || d.change_rate > 5)
                    return "#fff";
                else
                    return "#333";
                //if(d.change_rate<-threshold){
                //    return "#fff";
                //}
                //else if(d.change_rate>=-threshold && d.change_rate<0){
                //    return "#2CA02C";
                //}
                //else if(d.change_rate<=threshold && d.change_rate>0){
                //    return "#D62728";
                //}
                //else if(d.change_rate>threshold){
                //    return "#fff";
                //}
                //else{
                //    return "#333";
                //}
            }

            /**
             * 加载涨幅文本
             * @param text
             */
            function percenttext(text) {
                text.attr("x", function(d) {
                        return x(d.x);
                    })
                    .attr("y", function(d) {
                        return y(d.y) + 24;
                    })
                    .text(function(d) {
                        //if (d.percent < 0)
                        //    return (d.percent).toFixed(2) + "%";
                        //else
                        //    return "+" + (d.percent).toFixed(2) + "%";
                        if (d.change_rate < 0) {
                            return (d.change_rate).toFixed(2) + "%";
                        } else {
                            return "+" + (d.change_rate).toFixed(2) + "%";
                        }
                    })
                    .attr("dx", function(d) {
                        var cellwidth = x(d.x + d.dx) - x(d.x);
                        return cellwidth / 2;

                    })
                    .attr("text-anchor", "middle")
                    .attr("dy", function(d) {
                        var fontsize = Math.sqrt(d.dx + d.dy);
                        var cellheight = y(d.y + d.dy) - y(d.y);
                        return cellheight / 2 - 10;

                    })
                    .style("opacity", function(d) {
                        var cellwidth = x(d.x + d.dx) - x(d.x);
                        var cellheight = y(d.y + d.dy) - y(d.y);
                        var textWidth = this.getComputedTextLength();
                        if (cellwidth > textWidth && cellheight > 35) {
                            return 1;
                        } else {
                            return 0;
                        }

                    })
                    .style("font-size", function(d) {
                        // return Math.sqrt(d.dx+d.dy);
                        return "11px";
                    })
                    .style("font-family", "微软雅黑")
                    .style("font-weight", "bold")
                    .style("fill", function(d) {
                        return getColor(d);
                    });
            }

            /**
             * 画出每一个板块/股票的框
             * @param rect
             */
            function rect(rect) {
                rect.attr("x", function(d) {
                        return x(d.x);
                    })
                    .attr("y", function(d) {
                        return y(d.y);
                    })
                    .attr("width", function(d) {
                        return Math.abs(x(d.x + d.dx) - x(d.x));
                    })
                    .attr("height", function(d) {
                        return Math.abs(y(d.y + d.dy) - y(d.y));
                    })
                    .style("fill", function(d) {
                        return rectColor(d.change_rate);
                    });
            }

            /**
             * 面包屑导航
             * @param d
             * @returns {string}
             */
            function name(d) {
                return d.parent ? name(d.parent) + " > " + d.name : d.name;
            }


            $(".spinner").css("display", "none");

        });
    }
}]);
